<template>
  <div class="mainWrapper">
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/dataExpress' }"
        ><i class="lh fw_300 lh-seller"></i
      ></el-breadcrumb-item>
      <el-breadcrumb-item>B端-商户</el-breadcrumb-item>
      <el-breadcrumb-item>商户管理</el-breadcrumb-item>
    </el-breadcrumb>

    <div class="content_Box box-shadow">
      <div class="py_5 px_10">
        <el-row>
          <el-col :span="4">
            <el-button
              type="success"
              class="fl"
              @click="goToAdd()"
              round
              size="mini"
              >新增商户</el-button
            >
            <el-button type="default" @click="downloadOrder()" round size="mini"
              >导出</el-button
            >
          </el-col>
          <el-col :span="20">
            <el-form
              :inline="true"
              :model="ruleForm"
              class="form-inline fr"
              @keyup.enter.native="shearchBtn()"
            >
              <el-form-item
                ><el-input
                  size="mini"
                  class="w_110"
                  v-model="s_merchant_phone"
                  placeholder="手机号"
                ></el-input
              ></el-form-item>
              <!-- <el-form-item><el-input size="mini" class="w_150" v-model="s_name" placeholder="商户名称"></el-input></el-form-item> -->
              <el-form-item class="w_150">
                <el-autocomplete
                  class="inline-input"
                  v-model="business_name"
                  :fetch-suggestions="querySearch3"
                  placeholder="商户名称"
                  :trigger-on-focus="true"
                  @select="handleSelect3"
                  clearable
                ></el-autocomplete>
              </el-form-item>

              <el-form-item class="w_100">
                <el-select
                  @change="changeBtn"
                  v-model="selectValue"
                  placeholder="市"
                >
                  <!-- <el-option label="请选择" value=""></el-option> -->
                  <el-option
                    v-for="item in cityList"
                    :key="item.id"
                    :label="item.city_name"
                    :value="`${item.id}|${item.city_name}`"
                  ></el-option>
                </el-select>
              </el-form-item>

              <el-form-item>
                <el-autocomplete
                  size="mini"
                  class="w_200"
                  v-model="s_bd_nickname"
                  :fetch-suggestions="querySearch"
                  placeholder="销售"
                  :trigger-on-focus="true"
                  @select="handleSelect"
                  clearable
                ></el-autocomplete>
              </el-form-item>

              <el-form-item>
                <el-select
                  size="mini"
                  class="w_90"
                  v-model="s_status"
                  placeholder="商户状态"
                  clearable
                >
                  <el-option
                    v-for="item in state"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  ></el-option>
                </el-select>
              </el-form-item>

              <el-form-item>
                <el-select
                  size="mini"
                  class="w_90"
                  v-model="is_lh_housekeeper"
                  placeholder="灵活管家"
                  clearable
                >
                  <el-option label="灵活管家" value=""></el-option>
                  <el-option label="开通" value="1"></el-option>
                  <el-option label="关闭" value="2"></el-option>
                </el-select>
              </el-form-item>

              <el-form-item class="w_100">
                <el-select v-model="s_origin" placeholder="来源" clearable>
                  <el-option label="后台" value="1"></el-option>
                  <el-option label="小程序" value="2"></el-option>
                </el-select>
              </el-form-item>

              <el-form-item prop="date1">
                <el-date-picker
                  size="mini"
                  type="date"
                  class="w_120i"
                  value-format="yyyy-MM-dd"
                  placeholder="开始日期"
                  v-model="ruleForm.date1"
                ></el-date-picker> </el-form-item
              >~
              <el-form-item prop="date2">
                <el-date-picker
                  size="mini"
                  type="date"
                  class="w_120i"
                  value-format="yyyy-MM-dd"
                  placeholder="结束日期"
                  v-model="ruleForm.date2"
                ></el-date-picker>
              </el-form-item>
              <el-button
                size="mini"
                type="primary"
                class="round-right"
                @click="shearchBtn"
                native-type="button"
                >搜索</el-button
              >
              <el-button size="mini" round @click="resetBtn">重置</el-button>
            </el-form>
          </el-col>
        </el-row>
      </div>

      <div class="">
        <template>
          <el-table
            :data="merchantsList"
            stripe
            :row-class-name="RowTbodyClass"
            :header-row-class-name="RowHeaderClass"
            :cell-class-name="CellTbodyClass"
            :header-cell-class-name="CellHeaderClass"
          >
            <el-table-column
              prop="id"
              label="序号"
              width="60"
              align="center"
              type="index"
            ></el-table-column>
            <el-table-column
              prop="business_sn"
              label="商户编号"
              width="110"
              align="center"
            ></el-table-column>
            <el-table-column
              prop="name"
              label="商户名称"
              width="130"
              :show-overflow-tooltip="true"
            >
              <template slot-scope="{ row }">
                <span
                  class="pointer text-primary u"
                  @click="goMerchantEdit(row)"
                  >{{ row.name }}</span
                >
              </template>
            </el-table-column>
            <el-table-column
              prop="merchant_name"
              label="负责人手机号"
              width="110"
            >
              <template slot-scope="{ row }">
                <span>{{ row.merchant_phone }}</span>
              </template>
            </el-table-column>
            <el-table-column label="商户状态" width="80" align="center">
              <template slot-scope="{ row }">
                <span class="text-success" v-if="row.status == '1'">启用</span>
                <span class="text-danger" v-if="row.status == '2'">已停用</span>
                <span class="text-danger" v-if="row.status == '其他'"
                  >异常</span
                >
              </template>
            </el-table-column>
            <el-table-column label="灵活管家" width="80" align="center">
              <template slot-scope="{ row }">
                <span class="text-success" v-if="row.is_lh_housekeeper == '1'"
                  >开通</span
                >
                <span class="text-danger" v-if="row.is_lh_housekeeper == '2'"
                  >关闭</span
                >
              </template>
            </el-table-column>
            <el-table-column label="商户类别" width="80" align="center">
              <template slot-scope="{ row }">
                <span v-if="row.type == '1'">企业</span>
                <span v-if="row.type == '2'">个人</span>
              </template>
            </el-table-column>
            <el-table-column
              prop="merchant_name"
              label="商户负责人"
              width="120"
            ></el-table-column>
            <el-table-column
              prop="bd_name"
              label="销售"
              width="140"
            ></el-table-column>
            <el-table-column
              prop="add_time"
              label="创建时间"
              width="150"
            ></el-table-column>
            <el-table-column label="来源" width="80" align="center">
              <template slot-scope="{ row }">
                <span v-if="row.origin == '1'">后台</span>
                <span v-if="row.origin == '2'">小程序</span>
              </template>
            </el-table-column>
            <el-table-column
              prop="creater_name"
              label="创建人"
              width="100"
            ></el-table-column>
            <el-table-column label="操作" min-width="200" fixed="right">
              <template slot-scope="{ row, $index }">
                <!-- <el-link :underline="false" type="info" @click="goMerchantEdit(row)">详情</el-link> -->
                <el-link :underline="false" type="primary" @click="goEdit(row)"
                  >店铺管理</el-link
                >
                <el-link :underline="false" type="primary" @click="goUser(row)"
                  >账号管理</el-link
                >
                <el-link
                  :underline="false"
                  type="success"
                  v-if="row.status == '2'"
                  @click="redactBtn(row, $index)"
                  >开启</el-link
                >
                <el-link
                  :underline="false"
                  type="danger"
                  v-if="row.status == '1'"
                  @click="redactBtn(row, $index)"
                  >关店</el-link
                >
              </template>
            </el-table-column>
          </el-table>
          <!-- 分页组件 -->
          <!-- <page :total="total" :pageNums="pageNum" @pagedata="onChildValue"></page> -->
          <page
            :total="total"
            :pageNums="pageNum"
            :disableMountedFetch="true"
            @pagedata="onChildValue"
          ></page>
        </template>
      </div>
    </div>
    <!-- 商户状态-关闭弹框 -->
    <el-dialog
      :title="diaTitle"
      :visible.sync="StateShowStop"
      width="30%"
      :close-on-click-modal="false"
    >
      <div class="auditCentent">
        <span>关闭商户后，商户及关联的店铺将无法正常登录客户端平台</span>
      </div>
      <div slot="footer" class="dialog-footer">
        <span class="btnOK mr_20" @click="addMenuBtn(2)">确 定</span>
        <span class="resetBtn" @click="hiddenRY">取 消</span>
      </div>
    </el-dialog>

    <!-- 商户状态-开启弹框 -->
    <el-dialog
      :title="diaTitle"
      :visible.sync="StateShowStart"
      width="30%"
      :close-on-click-modal="false"
    >
      <div class="auditCentent">
        <span>开启商户后，商户及关联的店铺将正常登录客户端平台</span>
      </div>
      <div slot="footer" class="dialog-footer">
        <span class="btnOK mr_20" @click="addMenuBtn(1)">确 定</span>
        <span class="resetBtn" @click="hiddenRY">取 消</span>
      </div>
    </el-dialog>
  </div>
</template>

<script>
var common = require('../../../static/tool.js')
import { mainfun } from '../../../assets/js/main.js'

export default {
  name: 'MerchantsList',
  data() {
    return {
      dataMes: '',
      ids: '',
      index: '',
      windowSizeHeight: document.documentElement.clientHeight, //浏览器可视化窗口的大小
      screenHeight: document.documentElement.clientHeight,
      manageInfo: JSON.parse(sessionStorage.getItem('manageInfo')), //登录信息
      url: common.url,
      state: [
        // {id: '', name: '请选择'},
        { id: '1', name: '启用' },
        { id: '2', name: '已停用' }
      ],
      //搜索对应值
      business_id: '', //所属商户ID
      business_name: '', //所属商户name
      s_merchant_phone: '', //手机号
      s_bd_userid: '', //销售ID
      s_bd_nickname: '', //销售名字
      s_status: '', //商户状态 [1]启用[2]禁用
      is_lh_housekeeper: '', //是否开通灵活管家 [1]开通[2]关闭
      s_origin: '', //1 后台 2 小程序
      ruleForm: {
        date1: '', //开始时间
        date2: '' //结束时间
      },
      merchantsList: [], //商户列表
      BusinessUserList: [], //销售列表
      diaTitle: '', //弹框title
      StateShowStop: false, //人员状态-弹框关闭
      StateShowStart: false, //人员状态-弹框关闭
      selectValue: '', //获取id和value
      s_city_id: '',
      s_city_name: '',
      cityList: [], //城市列表

      //向分页组件传值
      total: 0,
      pageNum: 1,
      pageSizeNow: 20
    }
  },
  created() {
    if (!sessionStorage.getItem('manageInfo')) {
      // 判断是否登录
      window.location = 'login.html'
      return
    }
    this.getMerchants()
  },
  mounted() {
    this.getBusinessUser()
    this.getcityList()
  },
  methods: {
    //获取商户列表
    getMerchants() {
      let fn = new FormData()
      this.$http.post(this.url + '/business/listForSearch', fn).then(
        res => {
          // console.log(res.data.data);
          if (res.data.msg == '查询成功!' || res.data.code == '200') {
            if (res.data.data.list != null) {
              res.data.data.list.forEach(item => {
                item.value = item.name
              })
              this.merchantsLists = res.data.data.list
            } else {
              this.merchantsLists = []
            }
          } else if (res.data.code == '8886') {
            //code   8886  登录过期
            sessionStorage.clear()
            this.$alert('登录已过期，请重新登录 !', '提示', {
              confirmButtonText: '确定',
              callback: action => {
                window.location = 'login.html'
              }
            })
            return
          } else {
            this.$message.error(res.data.msg)
            return
          }
        },
        res => {
          this.$message.error('网络错误！')
          return
        }
      )
    },
    // s_bd_nickname
    listUser() {
      //获取用户列表
      let fn = new FormData()
      fn.append('pageSize', this.pageSizeNow) //每页多少条
      fn.append('page', this.pageNum) //页数
      fn.append('name', this.business_name)
      fn.append('merchant_phone', this.s_merchant_phone)
      //判断销售是否存在 this.dataMes.bd_name
      // if(this.s_bd_nickname!=""){
      //   var existence = false;//默认不存在
      //   this.BusinessUserList.forEach(item => {
      //       if(this.s_bd_nickname==item.nickname){
      //           existence = true;
      //       }
      //   });
      //   if(existence==false){
      //       // this.$message.error("请选择正确的销售");
      //       this.merchantsList = [];
      //       this.total = 0;
      //       return;
      //   }
      // }
      fn.append('bd_name', this.s_bd_nickname)
      fn.append('status', this.s_status)
      fn.append('origin', this.s_origin)
      fn.append('is_lh_housekeeper', this.is_lh_housekeeper)

      fn.append('city_id', this.s_city_id) //城市ID

      var ruleForm_date1 = ''
      var ruleForm_date2 = ''
      if (this.ruleForm.date1 == null) {
        this.ruleForm.date1 = ''
      }
      if (this.ruleForm.date2 == null) {
        this.ruleForm.date2 = ''
      }
      if (this.ruleForm.date1 != '' && this.ruleForm.date2 != '') {
        //开始时间与结束时间必须同时存在
        ruleForm_date1 = this.ruleForm.date1
        ruleForm_date2 = this.ruleForm.date2
      }

      fn.append('start_time', ruleForm_date1)
      fn.append('end_time', ruleForm_date2)

      this.$http.post(this.url + '/business/list', fn).then(
        res => {
          // console.log(res.data.data);
          if (res.data.msg == '查询成功' || res.data.code == '200') {
            if (res.data.data != null) {
              this.merchantsList = res.data.data.list
              this.total = res.data.data.count
            } else {
              this.merchantsList = []
              this.total = 0
            }
          } else if (res.data.code == '8886') {
            //code   8886  登录过期
            sessionStorage.clear()
            this.$alert('登录已过期，请重新登录 !', '提示', {
              confirmButtonText: '确定',
              callback: action => {
                window.location = 'login.html'
              }
            })
            return
          } else {
            this.$message.error(res.data.msg)
            return
          }
        },
        res => {
          this.$message.error('网络错误！')
          return
        }
      )
    },
    //获取销售列表
    getBusinessUser() {
      let fn = new FormData()
      this.$http.post(this.url + '/manageUser/getBusinessUser', fn).then(
        res => {
          // console.log(res.data.data);
          if (res.data.msg == '查询成功!' || res.data.code == '200') {
            if (res.data.data != null) {
              res.data.data.forEach(item => {
                item.value = item.nickname
              })
              this.BusinessUserList = res.data.data
            } else {
              this.BusinessUserList = []
            }
          } else if (res.data.code == '8886') {
            //code   8886  登录过期
            sessionStorage.clear()
            this.$alert('登录已过期，请重新登录 !', '提示', {
              confirmButtonText: '确定',
              callback: action => {
                window.location = 'login.html'
              }
            })
            return
          } else {
            this.$message.error(res.data.msg)
            return
          }
        },
        res => {
          this.$message.error('网络错误！')
          return
        }
      )
    },

    getcityList() {
      //获取城市列表
      let fn = new FormData()
      this.$http.post(this.url + '/city/list', fn).then(
        res => {
          if (res.data.msg == '查询成功' || res.data.code == '200') {
            var ret = res.data.data.list
            this.cityList = ret
            // `${item.id}|${item.city_name}`
            this.selectValue = `${ret[0].id}|${ret[0].city_name}`
            this.s_city_id = ret[0].id
            this.s_city_name = ret[0].city_name
            this.listUser()
          } else if (res.data.code == '8886') {
            //code   8886  登录过期
            sessionStorage.clear()
            this.$alert('登录已过期，请重新登录 !', '提示', {
              confirmButtonText: '确定',
              callback: action => {
                window.location = 'login.html'
              }
            })
            return
          } else {
            this.$message.error(res.data.msg)
            return
          }
        },
        res => {
          this.$message.error('网络错误！')
          return
        }
      )
    },

    shearchBtn() {
      // 搜索
      this.pageNum = 1
      this.listUser()
    },

    resetBtn() {
      this.selectValue = `${this.cityList[0].id}|${this.cityList[0].city_name}`
      this.s_city_id = this.cityList[0].id
      this.s_city_name = this.cityList[0].city_name
      //重置
      this.resetData() //重置请求数据
      this.pageNum = 1
      this.listUser()
    },

    resetData() {
      //重置请求数据
      this.pageNum = 1
      this.business_name = ''
      this.s_merchant_phone = ''
      this.s_bd_userid = ''
      this.s_bd_nickname = ''
      this.s_status = ''
      this.s_origin = ''
      this.ruleForm.date1 = ''
      this.ruleForm.date2 = ''
      this.is_lh_housekeeper = ''
    },

    goMerchantEdit(row) {
      //编辑页面
      this.$router.push({
        path: '/merchantsEdit',
        query: {
          id: row.id
        }
      })
    },

    goEdit(row) {
      // this.$router.push({
      //   path: '/shopList',
      //   query: {
      //     id: row.id,
      //     sn: row.business_sn,
      //     name: row.name,
      //     type: row.type,
      //   }
      // });

      const { href } = this.$router.resolve({
        path: '/shopList',
        query: { id: row.id, sn: row.business_sn, name: row.name, type: row.type }
      })
      window.open(href, '_blank')
    },

    goUser(row) {
      // this.$router.push({
      //   path: '/shopUserList',
      //   query: {
      //     id: row.id,
      //     sn: row.business_sn,
      //     name: row.name,
      //   }
      // });
      const { href } = this.$router.resolve({
        path: '/shopUserList',
        query: { id: row.id, sn: row.business_sn, name: row.name }
      })
      window.open(href, '_blank')
    },

    goToAdd() {
      //添加人员
      this.$router.push('/merchantsAdd')
    },

    //自动完成
    querySearch(queryString, cb) {
      var restaurants = this.BusinessUserList
      var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants
      // 调用 callback 返回建议列表的数据
      cb(results)
    },
    createFilter(queryString) {
      return restaurant => {
        return restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0
      }
    },
    handleSelect(item) {
      // console.log(item);
      this.s_bd_nickname = item.nickname
      this.s_bd_userid = item.user_id
    },
    //商户的自动完成
    querySearch3(queryString, cb) {
      var restaurants = this.merchantsLists
      var results = queryString ? restaurants.filter(this.createFilter3(queryString)) : restaurants
      // 调用 callback 返回建议列表的数据
      cb(results)
    },
    createFilter3(queryString) {
      return restaurant => {
        return restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0
      }
    },
    handleSelect3(item) {
      this.business_name = item.name
      this.business_id = item.id
    },
    //商户状态切换
    redactBtn(e, index) {
      this.dataMes = e
      this.ids = e.id
      this.index = index
      if (e.status == '1') {
        // 弹框1
        this.StateShowStop = true //状态关闭
        this.diaTitle = '温馨提示'
      } else {
        // 弹框2
        this.StateShowStart = true //状态开启
        this.diaTitle = '温馨提示'
      }
    },
    //隐藏商户弹框
    hiddenRY() {
      this.StateShowStart = false
      this.StateShowStop = false
    },
    // 商户状态-弹框确认
    addMenuBtn(e) {
      let fn = new FormData()
      fn.append('id', this.ids) //相关id
      fn.append('status', e) //商铺状态
      fn.append('type', this.dataMes.type)
      fn.append('name', this.dataMes.name)
      fn.append('merchant_name', this.dataMes.merchant_name)
      fn.append('merchant_phone', this.dataMes.merchant_phone)
      fn.append('industry', 1)
      fn.append('city_id', this.dataMes.city_id)
      fn.append('city_sn', this.dataMes.city_sn)
      fn.append('city_name', this.dataMes.city_name)

      this.$http.post(this.url + '/business/edit', fn).then(
        res => {
          // console.log(res);
          if (res.data.msg == '修改成功!' || res.data.code == '200') {
            this.$message.success(res.data.msg)
            this.listUser()
          } else if (res.data.code == '8886') {
            //code   8886  登录过期
            sessionStorage.clear()
            this.$alert('登录已过期，请重新登录 !', '提示', {
              confirmButtonText: '确定',
              callback: action => {
                window.location = 'login.html'
              }
            })
            return
          } else {
            this.$message.error(res.data.msg)
            //样式更换取消
            // this.renList[this.index].work_status=='1'?this.renList[this.index].work_status='2':this.renList[this.index].work_status='1'
            return
          }
        },
        res => {
          this.$message.error('网络错误！')
          //样式更换取消
          // this.renList[this.index].work_status=='1'?this.renList[this.index].work_status='2':this.renList[this.index].work_status='1'
          return
        }
      )

      //关闭弹框
      this.StateShowStop = false
      this.StateShowStart = false
    },
    //分页组件->子组件传值
    onChildValue(item) {
      this.pageNum = item[0]
      this.pageSizeNow = item[1]
      this.listUser()
    },

    CellClass(n) {
      switch (n) {
        case 0:
          return 'm-id'
        case 1:
          return 'title'
        case 2:
          return 'mobile'
        case 3:
          return ''
        case 4:
          return ''
        case 5:
          return ''
        case 6:
          return ''
        default:
          return 'm-cell-' + n
      }
    },

    downloadOrder() {
      //商户列表-导出
      var ruleForm_date1 = ''
      var ruleForm_date2 = ''
      if (this.ruleForm.date1 != '' && this.ruleForm.date2 != '') {
        //开始时间与结束时间必须同时存在
        ruleForm_date1 = this.ruleForm.date1
        ruleForm_date2 = this.ruleForm.date2
      }
      let obj = {
        token: JSON.parse(sessionStorage.getItem('manageInfo')).token,
        name: this.business_name,
        merchant_phone: this.s_merchant_phone,
        bd_userid: this.s_bd_userid,
        status: this.s_status,
        origin: this.s_origin,
        start_time: ruleForm_date1,
        end_time: ruleForm_date2
      }
      let param = $.param(obj)
      window.location.href = this.url + '/business/exportList?' + param
    },

    //数据行加class
    RowTbodyClass({ row, rowIndex }) {
      return 'merchants.css-row-' + rowIndex
    },
    //表头行添加class
    RowHeaderClass({ row, rowIndex }) {
      return 'merchants.css-header' + rowIndex
    },
    //每列单元格的样式
    CellTbodyClass({ columnIndex }) {
      return this.CellClass(columnIndex)
    },
    //每列表头的样式
    CellHeaderClass({ columnIndex }) {
      return this.CellClass(columnIndex)
    },
    changeBtn() {
      if (this.selectValue == '') {
        this.s_city_id = ''
        this.s_city_name = ''
        return false
      }
      let [id, name] = this.selectValue.split('|') // es6 数组解构赋值
      this.s_city_id = id
      this.s_city_name = name
    }
  },
  filters: {}
}
</script>

<style scoped>
@import '../../assets/style/merchants.css';
</style>



// WEBPACK FOOTER //
// src/components/merchants/MerchantsList.vue